import { Controller } from 'egg';
import { Result } from '../util';

import { uuidCommonRule } from './validate-rule';
import { API_PREFIX } from '../../constants/api';

class SMSVerificationController extends Controller {
  async send() {
    const { ctx } = this;

    ctx.validate({
      tel: {
        type: 'string',
      }
    }, ctx.query);

    const { tel } = ctx.query;
    const existResult = await this
      .ctx.service.smsVerification.findExistTel(
        tel
      );

    ctx.body = new Result({ existResult });
  }

  async verify() {
    const { ctx } = this;

    ctx.validate({
      tel: {
        type: 'string',
        max: 11,
        min: 11
      },
      code: {
        type: 'string',
        max: 6,
        min: 6
      },
      questionnaireUuid: uuidCommonRule,
    }, ctx.query);

    const {
      tel,
      code,
      questionnaireUuid: uuid,
    } = ctx.query;

    const verifyResult = await this
      .ctx
      .service
      .smsVerification
      .verify(
        tel, code
      );

    if (verifyResult) {
      ctx.redirect(`${API_PREFIX}/user/answerProgressState?tel=${tel}&uuid=${uuid}`);
    } else {
      ctx.body = new Result({ verifyMessageState: 0 });
    }
  }
}

module.exports = SMSVerificationController;
